// stores/login.js
import { defineStore } from 'pinia'
import { ref, watch, onMounted } from 'vue'
import api from '@/api/index'
import { ElMessage } from 'element-plus'

export const useLoginStore = defineStore('login', () => {
  // 定义状态
  const isLoggedIn = ref(false)
  const user = ref(null)
  const showLoginDialog = ref(false)

  // 登录动作
  async function login(params) {
    try {
      let res = await api.loginByCode({
        phone: params.phone,
        code: params.code,
      })
      let { data, code } = res
      if (code == 200) {
        isLoggedIn.value = true
        user.value = data
        // 将 Token 存储到 localStorage，便于以后请求时携带
        localStorage.setItem('authToken', data.token)
        ElMessage.success('登陆成功')
        return true
      } else {
        console.log(data)
      }
    } catch (error) {
      ElMessage.error('登录失败：' + error.response.data.message)
      console.error('登录失败:', error)
    }
  }

  // 注销动作
  function logout() {
    isLoggedIn.value = false
    user.value = null
    localStorage.removeItem('authToken')
  }

  // 显示登录框
  function show(){
    showLoginDialog.value = true
  }
  function hide(){
    showLoginDialog.value = false
  }

  // 初始化时尝试从 localStorage 加载用户状态
  onMounted(() => {
    const storedIsLoggedIn = localStorage.getItem('isLoggedIn')
    const storedUser = localStorage.getItem('user')

    if (storedIsLoggedIn === 'true') {
      isLoggedIn.value = true
      user.value = JSON.parse(storedUser)
    }
  })

  // 监听登录状态变化，当登录时将状态保存到 localStorage
  watch(isLoggedIn, (newValue) => {
    localStorage.setItem('isLoggedIn', newValue)
    if (newValue) {
      localStorage.setItem('user', JSON.stringify(user.value))
    } else {
      localStorage.removeItem('user')
    }
  })

  // 返回公共状态和方法
  return {
    isLoggedIn,
    user,
    login,
    logout,
    show,
    hide,
    showLoginDialog
  }
})
